function getapi(action){

	return  host+api[action];
}

function getpage(action){

	return  webindex+page[action];
}

function Popup(popoutcode){
    // <div class="box">
    //     <div class="box-header">
    //         <h3 class="box-title">Split buttons</h3>
    //     </div>
    //     <div class="box-body">
    //         <p>Normal split buttons:</p>
    //         <div class="margin">
    //             <div class="btn-group">
    //                <button type="button" class="btn btn-danger">Action</button>
    //             </div>
    //             <div class="btn-group">
    //                <button type="button" class="btn btn-success">Action</button>
    //             </div>
    //         </div>
    //     </div>
    // </div>

}


function addBox(data,field,button=[])
{
    //遍历result 
    $(".odd").remove();
    var listbody = '';

    $.each(data,function(rows,row){
            listbody +="<tr>"

            $.each(field,function(columns,column){

                if (isImg(row[column])) {
                    listbody +='<td><img src='+imghost+row[column]+' style="width: 100px;"></td>';
                }else{
                    if (column == 'id') window.localStorage.setItem("costmerid",row[column]);
                    else listbody +="<td>"+row[column]+"</td>"; //console.log(row[column]);
                } 
            });
            $.each(button,function(buttons,buttoncode){
                if ((buttoncode[0]!=''||buttoncode[0]!=null)&&(row['list_id']!=''||row['list_id']!=null)) listbody += '<td>'+buttoncode[0]+row['list_id']+buttoncode[1]+'</td>';
                else listbody += '<td>'+buttoncode+'</td>';
            });
            
            listbody += '</tr>'
        });

        $("#list").append(listbody);
}


function addSelect(data,field)//parent_id//ar_id
{

    var select = '<select class="form-control" name="'+field+'">';
     $.each(data,function(rows,row){
        select += '<option value="'+row.id+'">'+row.name+'</option>';
     });
    select += '</select>';

    $("#"+field).append(select);//$("#parent_id")//ar_id
}
function searchCode() {
    var code = $("#searchcode").val();
    if (code == "" || code == null || code == undefined) alert("请输入兑换码");
    window.location.href=getpage('searchcode')+"&code="+code

   // commonAjax("searchcode",3,filed,param);
}

function logout() {
    window.location.href = webhost;
    localStorage.removeItem('bid');
    //$('#logoutbtn').attr("href",webhost);
}

function refreshAction(action,data,field){
    //$("#actionbody").empty();
    $("#actionbody").load("./action/"+action+".html");

   // windows.location.href="http://webtest.local.com/public/index.html?1=1&action=searchcode"
     // console.log(data);
    // debugger;
     addBox(data,field);
    //commonAjax("searchcode",2,field);
}

function commonAjax(action,option='',field=[],parameter={},button=[])
{
	var postdata = {};
    postdata.q = JSON.stringify( parameter);
    postdata.sign = $.md5(postdata.q+safe_key);
    // console.log(postdata);
    $.ajax({
        url: getapi(action),
        type : 'POST',
        data:postdata,
        contentType: "application/x-www-form-urlencoded",
        
        success : function(result) {
            // var result = JSON.parse(result_str);
            // console.log(result);
            if (result.status =='timeout') {
                if (window.localStorage.getItem("logoutNotice")!=1) {
                    alert('登录超时');
                    window.location.href=webhost;
                }
                    window.localStorage.setItem("logoutNotice",1);
            }
            if (result.status =='no')   alert(result.message); 
            if (result.status !='ok')   alert(result.message); 
            if (option == 1) baseinfo(result.data);
        	if (option == 2) addBox(result.data,field,button);
            if (option == 3) refreshAction(action,result.data,field);
            if (option == 4) {
                var data_up = new Array();
                data_up[0] = result.data;
                addBox(data_up,field,button);
            }
            if (option == 5) {
                addSelect(result.data,field);
            }
            if (option == '') alert(result.message);
        },
        error: function() {
        	//window.location.href = webhost;
            alert('获取数据失败！请刷新页面');
        }
    })
}

function postFormDataAjax(action,formdata,jumpurl,Assignment)
{
    $.ajax({
      url: getapi(action),
      type : 'POST',
      data: formdata,
      async: false,          
      contentType: false,
      cache: false,   
      processData: false,
      success : function(data){ 
        if(data.status == "ok")
        {
          if(Assignment) 
          {
            // console.log(data.data,Assignment);
            //赋值
            $("#"+Assignment).val(data.data);
          }else{
            //跳转
            window.location.href = getpage(jumpurl);
          }
        }else{
          alert(data.message);
        }
      },
      error : function() {
        alert('操作失败！');
      }
    });
}

function baseinfo(){
    $(".businessname").text( window.localStorage.getItem("business_name"));
    $(".businesslogo").find('img').attr('src',imghost+window.localStorage.getItem("logo"));
}

function GetQueryString(name) {
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if(r!=null)return  unescape(r[2]); return null;
}


function  eachField(field)
{
    var str = '';
    $.each(field,function(index,obj){
        str +="<tr>"+"<td>"+obj.imgurl+"</td>";
    });
    return str;
}


function isImg(path)
{
    regex=/\./g;
    if (!regex.test(path)) return false;
    //console.log(path)
    var extStart = path.lastIndexOf('.'),
        ext = path.substring(extStart, path.length).toUpperCase();
    if (ext !== '.PNG' && ext !== '.JPG' && ext !== '.JPEG' && ext !== '.GIF')  
        return false;
    else
        return true;
}

function checkNumber(theObj) {
  var reg = /^[0-9]+.?[0-9]*$/;
  if (reg.test(theObj)) {
    return true;
  }
  return false;
}

function  urlEncode(param, key, encode) {  
  if(param==null) return '';  
  var paramStr = '';  
  var t = typeof (param);  
  if (t == 'string' || t == 'number' || t == 'boolean') {  
    paramStr += '&' + key + '=' + ((encode==null||encode) ? encodeURIComponent(param) : param);  
  } else {  
    for (var i in param) {  
      var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);  
      paramStr += urlEncode(param[i], k, encode);  
    }  
  }  
  return paramStr;  
}; 

 